package com.scud.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.scud.common.error.ErrorConstants;
import com.scud.common.exception.ScudException;
import com.scud.common.regex.RegexPatterns;
import com.scud.model.system.dto.LoginDto;
import com.scud.model.system.pojo.User;
import com.scud.system.mapper.UserMapper;
import com.scud.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("password_auth")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User execute(LoginDto loginDto) {
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        //校验手机号
        if (StrUtil.isBlank(phone) || !phone.matches(RegexPatterns.PHONE_REGEX)) {
            throw new ScudException(ErrorConstants.PHONE_ILL_LEGAL);
        }
        //密码为空
        if (StrUtil.isBlank(password)){
            throw new ScudException(ErrorConstants.PASSWORD_ERROR);
        }
        User user = userMapper.getUserByPhone(phone);
        if (Objects.isNull(user)){
            //用户不存在，直接注册
            user = User.builder().phone(phone).password(passwordEncoder.encode(password))
                    .status(1).build();
            userMapper.insertUser(user);
        }else {
            //校验密码
            if (!passwordEncoder.matches(password, user.getPassword())){
                throw new ScudException(ErrorConstants.PASSWORD_ERROR);
            }
        }
        return user;
    }
}
